package com.rg.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtils {
    //定义数据库连接池数据源
    private  static DruidDataSource druidDataSource;
    //初始化数据库连接池
    static {
        try{
            //读取druid配置文件
            InputStream is =DruidUtils.class.getResourceAsStream("druid.properties");
            //新建配置文件对象
            Properties properties = new Properties();
            //把文件以输入流的形式加载到配置文件中
            properties.load(is);
            //创建数据源对象
            druidDataSource=(DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        }catch (IOException e){
            throw new RuntimeException(e);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
    //返回数据源对象
    public static DataSource getDataSource(){
        return druidDataSource;
    }
    //获取数据库连接
    public static Connection getConnection(){
        Connection connection=null;
        try{
            connection=druidDataSource.getConnection();
        }catch (SQLException e){
            throw new RuntimeException(e);
        }
        return connection;
    }
}
